<?php namespace App\Services;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;

class ApiConfigService
{

    public function __construct()
    {
        $dir = __DIR__ . "/../../config/validate/";

        $files = new Filesystem();
        $configs = $files->glob($dir . "api.*.php");
        foreach ($configs as $config) {
            $pathInfo = pathinfo($config);
            $filename = $pathInfo['filename'];
            app()->configure($filename);
        }

    }

    protected function addRoutes()
    {
        $apiDefs = config('api');

        foreach ($apiDefs as $apiDef) {
            foreach ($apiDef['methods'] as $method) {

                $action = [
                    'uses' => $apiDef['controller'] . '@' . $method['method'],
                ];

                $action['middleware'] = [];
                if (isset($method['middleware'])) {
                    $action['middleware'] = $method['middleware'];
                }
                array_push($action['middleware'], 'api');

                app()->addRoute($method['requestMethod'], $method['requestRoute'], $action);
            }
        }
    }

    public function getValidations($controller, $method)
    {

        $methodDef = $this->getMethodDef($controller, $method);
        if (isset($methodDef) && isset($methodDef['inputs'])) return $methodDef['inputs'];

        return null;
    }

    public function getErrorMessage($controller, $method, $code)
    {
        $methodDef = $this->getMethodDef($controller, $method);
        if (isset($methodDef) && isset($methodDef['errors']) && !empty($methodDef['errors'])) {
            foreach($methodDef['errors'] as $errorDef) {
                if ($errorDef['code'] == $code) return $errorDef['message'];
            }
        }

        return $code;
    }

    public function getObjectInputs($controller, $method)
    {
        $ret = [];
        $methodDef = $this->getMethodDef($controller, $method);

        if (isset($methodDef) && isset($methodDef['inputs']) && !empty($methodDef['inputs'])) {
            foreach ($methodDef['inputs'] as $inputDef) {
                if (isset($inputDef['type']) && $inputDef['type'] == 'object')
                    $ret[] = $inputDef['field'];
            }
        }

        return $ret;
    }

    protected function getMethodDef($controller, $method)
    {

        $apiDefs = config('api');
        foreach ($apiDefs as $apiDef) {
            if (!Str::equals($apiDef['controller'], $controller)) continue;

            foreach ($apiDef['methods'] as $methodDef) {
                if (!Str::equals($methodDef['method'], $method)) continue;

                return $methodDef;
            }
        }

        return null;
    }

}